﻿using System.Collections.ObjectModel;
using System.Collections.Specialized;
using UTable.Core.Windows;

namespace UTable.Core.Input
{
    /// <summary>
    /// This class includes all of the provider of UTable
    /// </summary>
    public class CompositeInputProvider : IInputProvider
    {
        #region Private Members

        private ObservableCollection<IInputProvider> _providers;

        #endregion

        #region Properties

        public ObservableCollection<IInputProvider> Providers { get { return _providers; } }

        #endregion

        #region Constructor

        public CompositeInputProvider()
        {
            _providers = new ObservableCollection<IInputProvider>();
            _providers.CollectionChanged += ProvidersCollectionChanged;
        }

        #endregion

        #region Private Methods

        private void ProvidersCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
        {
            switch (e.Action)
            {
                case NotifyCollectionChangedAction.Add:
                    foreach (object o in e.NewItems)
                        OnProviderAdded(o as IInputProvider);
                    break;
                case NotifyCollectionChangedAction.Remove:
                    foreach (object o in e.OldItems)
                        OnProviderRemoved(o as IInputProvider);
                    break;
                case NotifyCollectionChangedAction.Replace:
                    for (int i = 0; i < e.NewItems.Count; ++i)
                    {
                        OnProviderAdded(e.NewItems[i] as IInputProvider);
                        OnProviderRemoved(e.OldItems[i] as IInputProvider);
                    }
                    break;
            }
        }

        private void OnProviderAdded(IInputProvider provider)
        {
            provider.InputTriggered += ProviderInputTriggered;
        }

        private void OnProviderRemoved(IInputProvider provider)
        {
            provider.InputTriggered -= ProviderInputTriggered;
        }

        private void ProviderInputTriggered(InputEventArgs args)
        {
            if (InputTriggered != null)
                InputTriggered(args);
        }

        #endregion

        #region IInputProvider Methods

        public event InputEventHandler InputTriggered;

        public void Initialize(UApplication context) { }

        #endregion
    }
}
